package com.eascs.afterloancheck.controller;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.dubbo.config.annotation.Reference;
import com.eascs.admin.o2o.internal.util.BaseUtils;
import com.eascs.admin.o2o.internal.util.BeanUtils;
import com.eascs.admin.o2o.loan.entity.O2oLoanUserEntity;
import com.eascs.admin.o2o.loan.entity.O2oLoanapplyEntity;
import com.eascs.admin.o2o.loan.service.O2oLoanUserService;
import com.eascs.admin.o2o.loan.service.O2oLoanapplyService;
import com.eascs.afterloancheck.dubbo.LoanCheckTask;
import com.eascs.afterloancheck.entity.CheckLoanEntity;
import com.eascs.afterloancheck.form.CheckLoanForm;
import com.eascs.afterloancheck.form.CheckLoanQueryForm;
import com.eascs.afterloancheck.form.ProcessStartForm;
import com.eascs.afterloancheck.service.LoanCheckServicce;
import com.eascs.app.dao.PageResult;
import com.eascs.app.log.Logger;
import com.eascs.app.log.LoggerFactory;
import com.eascs.common.util.UrlUtil;
import com.eascs.crm.common.service.ICustomerInfoService;
import com.eascs.crm.common.service.ICustomerShopService;
import com.eascs.crm.common.vo.QueryCustomerVO;
import com.eascs.crm.common.vo.ShopMarketMoneyRequest;
import com.eascs.crm.nsEditDetail.entity.CustomerShopInfoEntity;
import com.eascs.crm.nsEditDetail.service.CustomerShopInfoService;
import com.eascs.file.FileTypeConstants;
import com.eascs.loan.entity.O2oBankLoanData;
import com.eascs.loan.service.O2oLoanService;
import com.eascs.site.controller.BaseRestController;
import com.eascs.site.page.PaginationInfo;
import com.eascs.site.page.SelectDataOption;
import com.eascs.site.view.BaseRestResult;
import com.eascs.site.view.HtmlRestResult;
import com.eascs.site.view.PaginationRestResult;
import com.eascs.site.view.ViewContext;
import com.eascs.site.view.button.AjaxConfirmButton;
import com.eascs.site.view.button.Button;
import com.eascs.site.view.button.ButtonHelper;
import com.eascs.web.sso.User;
import com.eascs.web.sso.UserHolder;
import com.eascs.workflow.common.entity.wf.ProcessTemplate;
import com.eascs.workflow.common.service.sequence.SequenceService;
import com.eascs.workflow.common.service.sys.SysOrgService;
import com.eascs.workflow.common.vo.ModelResult;

@RestController
@RequestMapping("/rafterloancheck")
public class AfterLoanCheckRestController extends BaseRestController {
	private Logger logger = LoggerFactory.getLogger(this.getClass());
	private final static String REVISIT_TYPE_CHECK = "CHECK_LOAN_AFTER";
	
	@Autowired
	private O2oLoanService o2oLoanService;
	
	@Autowired
	private O2oLoanUserService o2oLoanUserService;
	
	@Autowired
	private BaseUtils baseUtils;
	
	@Autowired
	private O2oLoanapplyService o2oLoanapplyService;
	
	@Reference
	private SequenceService SequenceService;
	
	@Autowired
	private LoanCheckServicce loanCheckServicce;
	
	@Reference
	ICustomerShopService iCustomerShopService;
	
	@Autowired
	CustomerShopInfoService customerShopInfoService;
	
	@Reference(retries=3)
	ICustomerInfoService iCustomerInfoService;
	
	
	@Reference
	SysOrgService sysOrgService;
	
	@Autowired
	private O2oLoanapplyService o2oloanapplyService;
	@Value("${o2o.admin.agreeUrlShow}")
	private String agreeUrlShow;
	@RequestMapping("/list")
	public PaginationRestResult checkList(CheckLoanQueryForm form) {
		form.setPageSize(10);
		
		List<User> users=sysOrgService.checkDataPermission(UserHolder.getUser().getNo());
		String no="";
		if (users!=null) {
			for (User user : users) {
				no+=user.getNo()+",";
			}
		}
		if (!"".equals(no)) {
			if (",".equals(no.substring(no.length()-1, no.length()))) {
				no=no.substring(0, no.length()-1);
			}
		}
		logger.info("userno={}", no);
		form.setXdjlNo(no);
		
		
		String checkurl = "/rafterloancheck/list";
		checkurl = form.getBillCode() == null ? UrlUtil.appendUrl(checkurl, "billCode", "") : UrlUtil.appendUrl(checkurl, "billCode", form.getBillCode());
		checkurl = form.getLoanUserName() == null ? UrlUtil.appendUrl(checkurl, "loanUserName", "") : UrlUtil.appendUrl(checkurl, "loanUserName", form.getLoanUserName());
		checkurl = form.getOrgManager() == null ? UrlUtil.appendUrl(checkurl, "orgManager", "") : UrlUtil.appendUrl(checkurl, "orgManager", form.getOrgManager());
		checkurl = form.getRevisiterName() == null ? UrlUtil.appendUrl(checkurl, "revisiterName", "") : UrlUtil.appendUrl(checkurl, "revisiterName",form.getRevisiterName());
		checkurl = checkurl + "&pageIndex=";
		String titles[] = {"回访单号", "贷款单号", "借款人姓名", "信贷经理","贷款类型", "回访人", "回访日期", "创建时间", "流程状态"};
		SelectDataOption[] selectDataOptions = { null, null, null, null,new SelectDataOption("OTO_LOAN_TYPE"), null ,null, null, new SelectDataOption("parWFStutus")};
		Button[] Button = new Button[] { ButtonHelper.createAjaxButton(null, "/rafterloancheck/view_detail?id="), null };
		PageResult<Object[]> pageResult= loanCheckServicce.queryListPage(form);
		PaginationInfo PagingInfo = new PaginationInfo(pageResult, titles, checkurl);
		PagingInfo.setBuildPagingNavigation(true);
		PagingInfo.setFirstRenderColumnIndex(1);
		PagingInfo.setTitleButtons(Button);
		PagingInfo.setRendTo("#result_list");
		PagingInfo.setSelectDataOptions(selectDataOptions);
		/*Button startFlow = ButtonHelper.createAjaxButton("发起流程", "/rafterloancheck/startCheck?id=","startCheck");// parameter为合作方id
		startFlow.setPermissionCode("dhdqjcStartFlow");
		startFlow.setShowButtonFilter(new ShowButtonFilter() {
			@Override
			public boolean filter(Object param) {
				Object[] params = (Object[]) param;
				if ("3".equals(params[9]+"")) 
					return true;
				else
					return false;
			}
		});
		
		Button[] morButtons = new Button[] {startFlow};
		PagingInfo.setMoreButtons(morButtons);*/
		ViewContext.put("form", form);
		return PaginationRestResult.buildPaginationRestResult(PagingInfo);
	}
	
	@RequestMapping("/startCheck")
	public BaseRestResult<String> startFlow(ProcessStartForm form) {
		logger.info("开始启动定期贷后检查,CheckLoanForm:[{}]", form.toString());
		if (form.getBillCode() == null && form.getId() != null) {
			form.setBillCode(loanCheckServicce.queryEntityById(form.getId()).getBillCode());
		}
		O2oLoanapplyEntity loanapply = o2oloanapplyService.fingByBillCode(form.getBillCode());
		CheckLoanEntity entity = new CheckLoanEntity();
		entity.setCreateDate(new Date());
		entity.setBillCode(loanapply.getBillCode());
		entity.setSponsorName(UserHolder.getUser().getCname());
		entity.setSponsorId(UserHolder.getUser().getNo());
		entity.setRevisitType(REVISIT_TYPE_CHECK);
		entity.setLoanApplyNo(loanapply.getLoanapplyNo());
		entity.setOrgManager(loanapply.getOperatorName());
		entity.setOrgManagerId(loanapply.getOperatorNo());
		entity.setLoanType(loanapply.getLoanType());
		O2oLoanUserEntity loanUser = o2oLoanUserService.findById(loanapply.getLoanId(), loanapply.getLoanapplyNo());
		entity.setLoanUserName(loanUser.getUserFullName());
		entity.setLoanId(loanapply.getLoanId());
		entity.setLtd(loanapply.getLtd());
		Integer loanNum = loanCheckServicce.queryLoanNum(loanapply.getLoanId());
		entity.setLoanNumber(loanNum);
		QueryCustomerVO vo = new QueryCustomerVO();
		vo.setCustomer_id(entity.getLoanId());
		ShopMarketMoneyRequest shopMarketMoneyRequest = new ShopMarketMoneyRequest(); 
		shopMarketMoneyRequest.setCustomerId(entity.getLoanId());
		CustomerShopInfoEntity customerShopInfoEntity =new CustomerShopInfoEntity();
		customerShopInfoEntity.setLoanapplyNo(entity.getLoanApplyNo());
		logger.info("------1111----customerShopInfoService :,CustomerShopId:[{}]", entity.getLoanApplyNo());
		com.eascs.crm.common.vo.ModelResult<CustomerShopInfoEntity> shopMarketMoney = customerShopInfoService.getShopMarketMoney(customerShopInfoEntity);
		CustomerShopInfoEntity model = shopMarketMoney.getModel();
		logger.info("------2222----customerShopInfoService :,CustomerShopId:[{}]", model.toString());
		if (shopMarketMoney.isSuccess() && model != null) {
			if (model.getTotalAmount() != null) {
				entity.setYearlySale(model.getTotalAmount().floatValue());
			}
			if (model.getShoptock() != null) {
				entity.setStockMoney(Float.valueOf(model.getShoptock()));
			}
		} else {
			BaseRestResult.warn(shopMarketMoney.getErrMsg());
		}
		String seq = SequenceService.getSeq("LOAN_CHECK_NO", 5, "DHDQJC-"+ new SimpleDateFormat("yyMMdd").format(new Date()));
		entity.setRevisitCode(seq);
		//启动定期贷后检查
		ModelResult<Boolean> modelResult = loanCheckServicce.insertCheckLoanEntity(entity);
		if (modelResult.isSuccess() && modelResult.getModel() != null) {
			return BaseRestResult.info("流程启动成功").andRefresh();
		}
		return BaseRestResult.warn(modelResult.getErrMsg());
	}	
	
	@RequestMapping("/view_detail")
	public BaseRestResult<String> viewFlow(String id) {
		CheckLoanEntity queryEntity = loanCheckServicce.queryEntityById(id);
		String processType=ProcessTemplate.PROECESS_TYPE_REGULAR_CHECK_LOAN_AFTER;
		String agreeUrl = agreeUrlShow+queryEntity.getLoanApplyNo()+"&processType="+processType;
		ViewContext.put("agreeUrl", agreeUrl);
		ViewContext.put("parameter", queryEntity.getLoanApplyNo());
		ViewContext.put("queryEntity", queryEntity);
		return HtmlRestResult.popHtmlFragment("/afterloancheck/check_detail");
	}
	
	
	
	@RequestMapping("/view_flow")
	public BaseRestResult<String> viewFlow(String approvalStatus, String referId, String nodeAuditorId) {
		String approvalUrl = baseUtils.getApprovalUrl(nodeAuditorId, ProcessTemplate.PROECESS_TYPE_PARTNERS_AUDIT_BP);// 审批代办列表详情URL
		CheckLoanEntity entity = loanCheckServicce.queryEntityByReferId(referId);
		String agreeUrl = baseUtils.getApprovalAgreeUrl(referId, nodeAuditorId, ProcessTemplate.SYSTEM_MODULE_O2O);
		O2oLoanapplyEntity loanapply = o2oLoanapplyService.fingByBillCode(entity.getBillCode());
		O2oBankLoanData bankData = o2oLoanService.queryBillCode(loanapply.getBillCode());
		O2oLoanUserEntity loanUser = o2oLoanUserService.findById(loanapply.getLoanId(), loanapply.getLoanapplyNo());
		ViewContext.put("loanUser", loanUser);
		ViewContext.put("bankData", bankData);
		ViewContext.put("loanapply", loanapply);
		ViewContext.put("approvalUrl", approvalUrl);
		ViewContext.put("agreeUrl", agreeUrl);
		ViewContext.put("approvalStatus", approvalStatus);// 流程经办状态是待办/已办/已发起，待办状态才显示审批栏
		ViewContext.put("vo", entity);
		return HtmlRestResult.popHtmlFragment("/afterloancheck/check_flow");
	}
	
	@RequestMapping("/dynamicForm")
	public HtmlRestResult rbackfeePrint(String referId,String nodeCode) {
		CheckLoanEntity entity = loanCheckServicce.queryEntityByReferId(referId);
//		User user = UserHolder.getUser();
//		entity.setRevisiterName(user.getCname());
//		entity.setRevisiterId(user.getNo());
		ViewContext.put("vo", entity);
		ViewContext.put("referId", referId);
		if (StringUtils.equals(nodeCode, "creditManager")) {
			ViewContext.put("isSave", "true");
		}
		return HtmlRestResult.html("/afterloancheck/dynamic_form");
	}
	
	/**
	 * 局部加载上传附件
	 * @return
	 */
	@RequestMapping("/loadfile")
	public HtmlRestResult querySQBZJFile(String id,String isSave,String loanId) {
		queryDataList(id, FileTypeConstants.LOAN_CHECK_TYPE_RPMENT,null);
		ViewContext.put("id", id);
		ViewContext.put("isSave", isSave);
		ViewContext.put("loanId", loanId);
		return HtmlRestResult.html("/afterloancheck/checkfile");
	}
	
	/**
	 * 附件列表
	 * @param loanapplyNo
	 * @param code
	 * @param detailFlag
	 */
	public void queryDataList(String loanapplyNo, String code, String detailFlag) {
		PageResult<Object[]> pageResult = o2oLoanapplyService.findO2oDataListEntityById(loanapplyNo, "'" + code + "'");
		String titles[] = { "附件类型", "文件名", "提交人", "提交时间", "更新时间" };
		Button[] titleButtons = new Button[] { null,
				ButtonHelper.createOpenButton(null, "/file/download?datalistno=") };
		PaginationInfo paginationInfo = new PaginationInfo(pageResult, titles);
		if (!"detail".equals(detailFlag)) {
		AjaxConfirmButton[] dealButton=null;
		dealButton = new AjaxConfirmButton[] { new AjaxConfirmButton("删除 ", "/loanrest/delete/") };
		paginationInfo.setMoreButtons(dealButton);
		}
		paginationInfo.setTitleButtons(titleButtons);
		paginationInfo.setBuildPagingNavigation(false);
		paginationInfo.setFirstRenderColumnIndex(1);
		paginationInfo.setBuildRowNumber(true);
		ViewContext.put("pageResult", paginationInfo);// 个人附件
	}
	
	
	
	@RequestMapping("/save_checkData")
	public BaseRestResult<String> saveEdit(CheckLoanForm form) {
		CheckLoanEntity entity = new CheckLoanEntity();
		BeanUtils.copyProperties(form, entity);		
		ModelResult<Boolean> model = loanCheckServicce.update(entity);
		if (model.isSuccess() && model.getModel()) {
			return BaseRestResult.info("保存成功");
		}
		return BaseRestResult.info(model.getErrMsg());
	}
	
	@Autowired
    LoanCheckTask loanCheckTask;
	@RequestMapping("test")
	public BaseRestResult<String> test () {
		loanCheckTask.autoStartUpLoanCheck();
		return null;
	}
	
	
	
}
